package com.haoxuewa.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haoxuewa.entity.EssayTemp;
import com.haoxuewa.service.AdminService;
import com.haoxuewa.service.EssayService;
import com.haoxuewa.service.EssayTempService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
public class EssayController {

    private final EssayService essayService;
    private final EssayTempService essayTempService;
    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    @Autowired
    public EssayController(EssayService essayService, EssayTempService essayTempService) {
        this.essayService = essayService;
        this.essayTempService = essayTempService;
    }

    @GetMapping("/ddd")
    public String ddd() {
        System.out.println("ddd");
        return "ddd";
    }

    // 通过审核
    @PostMapping("/essayAuditPass")
    public String essayAuditPass(@RequestBody Map<String, String> map) {
        System.out.println(map.get("essayId"));
        JSONObject jsonObject = new JSONObject();
        if (essayService.EssayAuditPass(Integer.parseInt(map.get("essayId")))) jsonObject.put("code", "200");
        else jsonObject.put("code", "403");
        return jsonObject.toString();
    }

    // 未通过审核
    @PostMapping("/essayAuditUnPass")
    public String essayAuditUnPass(@RequestBody Map<String, String> map) {
        System.out.println("essayAuditPass");
        JSONObject jsonObject = new JSONObject();
        String url = essayService.getPicture(Integer.parseInt(map.get("essayId")));
        if (essayTempService.EssayAuditUnPass(Integer.parseInt(map.get("essayId")))) {
            //从本地硬盘删除已经上传的图片
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            File file = new File(UPLOAD_FOLDER + fileName);
            //判断此文件是否为空
            //文件不为空，执行删除
            file.delete();
            jsonObject.put("code", "200");
        } else jsonObject.put("code", "403");
        return jsonObject.toString();
    }

    //取插本基础课数据
    @GetMapping("/getCBBasic")
    public String getCBBasic() {
        System.out.println("ddd");
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> list = essayService.cbBasicCourse();
        jsonObject.put("data", list);
        return jsonObject.toString();
    }

    //取插本专业课数据
    @GetMapping("/getCBSpecialize")
    public String getSpecialize() {
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> list = essayService.cbSpecializeCourse();
        jsonObject.put("data", list);
        return jsonObject.toString();
    }
}
